package com.pfzy.lib.sdk.permission;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.SparseArray;

import com.pfzy.lib.sdk.permission.callback.PermissionInterface;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public final class PermissionFragment extends Fragment {
    private static final String PERMISSION_GROUP = "permission_group";
    private static final String REQUEST_CODE = "request_code";
    private static final SparseArray<PermissionInterface> sContainer = new SparseArray<>();

    public static PermissionFragment newInstant(Activity activity, ArrayList<String> permissions2) {
        int requestCode;
        if (activity.getFragmentManager().findFragmentByTag(PermissionFragment.class.getName()) instanceof PermissionFragment) {
            return (PermissionFragment) activity.getFragmentManager().findFragmentByTag(PermissionFragment.class.getName());
        }
        PermissionFragment fragment = new PermissionFragment();
        Bundle bundle = new Bundle();
        do {
            requestCode = new Random().nextInt(255);
        } while (sContainer.get(requestCode) != null);
        bundle.putInt(REQUEST_CODE, requestCode);
        bundle.putStringArrayList(PERMISSION_GROUP, permissions2);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 准备请求
     * @param activity
     * @param call
     */
    public void prepareRequest(Activity activity, PermissionInterface call) {
        sContainer.put(getArguments().getInt(REQUEST_CODE), call);
        if (!(activity.getFragmentManager().findFragmentByTag(PermissionFragment.class.getName()) instanceof PermissionFragment)) {
            activity.getFragmentManager().beginTransaction().add(this, PermissionFragment.class.getName()).commitAllowingStateLoss();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        requestPermission();
    }

    /**
     * 请求权限
     */
    public void requestPermission() {
        if (PermissionUtils.isOverMarshmallow()) {
            ArrayList<String> permissions2 = getArguments().getStringArrayList(PERMISSION_GROUP);
            requestPermissions((String[]) permissions2.toArray(new String[permissions2.size() - 1]), getArguments().getInt(REQUEST_CODE));
        }
    }

    /**
     * 请求权限结果
     * @param requestCode
     * @param permissions2
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions2, int[] grantResults) {
        PermissionInterface call = sContainer.get(requestCode);
        if (call != null) {
            List<String> succeedPermissions = PermissionUtils.getSucceedPermissions(permissions2, grantResults);
            if (succeedPermissions.size() == permissions2.length) {
                call.hasPermission(succeedPermissions, true);
            } else {
                List<String> failPermissions = PermissionUtils.getFailPermissions(permissions2, grantResults);
                call.noPermission(failPermissions, PermissionUtils.checkMorePermissionPermanentDenied(getActivity(), failPermissions));
                if (!succeedPermissions.isEmpty()) {
                    call.hasPermission(succeedPermissions, false);
                }
            }
            sContainer.remove(requestCode);
            getFragmentManager().beginTransaction().remove(this).commitAllowingStateLoss();
        }
    }
}
